package com.jyu.work.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jyu.common.context.BaseContext;
import com.jyu.common.result.Result;
import com.jyu.pojo.DTO.ShoppingCartDTO;
import com.jyu.pojo.entity.ShoppingCart;
import com.jyu.work.service.IShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author guancheng
 * @since 2023-11-30
 */
@RestController
@RequestMapping("/shoppingCart")
@CrossOrigin(origins = "http://127.0.0.1:5173")

public class ShoppingCartController {
    @Autowired
    private IShoppingCartService shoppingCartService;

    @DeleteMapping
    public Result del(int[] ids) {
        for (int i = 0; i < ids.length; i++) {
            int index = ids[i];
            System.out.println(index + "===========");
            shoppingCartService.removeById(index);
        }

        return Result.success(null, "删除成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody ShoppingCart shoppingCart) {
        shoppingCartService.save(shoppingCart);
        return Result.success(null, "添加成功");
    }


    @PutMapping
    public Result updateShoppingCart(@RequestBody ShoppingCart shoppingCart){
        Long currentId = BaseContext.getCurrentId();
        shoppingCartService.update(shoppingCart, new LambdaQueryWrapper<ShoppingCart>()
                        .eq(ShoppingCart::getProductId,shoppingCart.getProductId())
                        .eq(ShoppingCart::getUserId,currentId));

        return Result.success(null, "修改成功");
    }


    @GetMapping
    public Result showShoppingCart(){
        Long currentId = BaseContext.getCurrentId();

        List<ShoppingCart> list = shoppingCartService.list(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, currentId));
        return Result.success(list, "查询成功");
    }

}

